package com.jn.fastjson.views;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

import com.jn.fastjson.R;

import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnBookDetail = findViewById(R.id.btn_book_detail);
        Button btnOlympicMedal = findViewById(R.id.btn_olympic_medal);
        Button btnHotSearch = findViewById(R.id.btn_hot_search);

        btnBookDetail.setOnClickListener(v -> {
            String bookJsonString = loadJsonFromAsset("book.json");
            Intent intent = new Intent(MainActivity.this, BookDetailActivity.class);
            intent.putExtra("book_json", bookJsonString);
            startActivity(intent);
        });

        btnOlympicMedal.setOnClickListener(v -> {
            String olympicJsonString = loadJsonFromAsset("olympic.json");
            Intent intent = new Intent(MainActivity.this, OlympicMedalActivity.class);
            intent.putExtra("olympic_json", olympicJsonString);
            startActivity(intent);
        });

        btnHotSearch.setOnClickListener(v -> {
            String hotSearchJsonString = loadJsonFromAsset("hotsearch.json");
            Intent intent = new Intent(MainActivity.this, HotSearchActivity.class);
            intent.putExtra("hotsearch_json", hotSearchJsonString);
            startActivity(intent);
        });
    }

    private String loadJsonFromAsset(String fileName) {
        String json = null;
        try (InputStream is = getAssets().open(fileName)) {
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return json;
    }
}
